<template>
  <view>

    <u-loading-page v-if="loading"></u-loading-page>
    <scroll-view v-else scroll-y style="height: 100vh">
      <u-navbar
          :autoBack="true"
          leftIconColor="white"
          :title-style="{color: 'black'}"
          bgColor="transparent"
      >
      </u-navbar>

      <user-not-exist v-if="!exist"></user-not-exist>
      <view v-else>
        <view
            :style="{backgroundImage: 'url(' + userInfo.backgroundUrl + ')'}"
            @tap="toAlterBackgroud(userInfo.backgroundUrl)"
            class="container">
          <view>
            <view class="userinfo" :style="{height: bgHeight }">
              <view class="avatar">
                <image @tap.stop="toAlterAvatar(userInfo.avatar)" :src="userInfo.avatar"></image>
              </view>
              <view class="name">
                <text>{{ userInfo.username }}</text>
              </view>
            </view>
          </view>
        </view>
        <!--    登录-->
        <view class="content">
          <view class="info">
            <view class="relation">
              <view style="display: flex;align-items: center">
                <view>
                  <text class="relation-number">{{checkParam(userInfo.likes)}}</text>
                  <text class="relation-item">&nbsp;获赞</text>
                </view>&nbsp;&nbsp;
                <view>
                  <text class="relation-number">{{checkParam(userInfo.friends)}}</text>
                  <text class="relation-item">&nbsp;朋友</text>
                </view>&nbsp;&nbsp;
                <view>
                  <text class="relation-number">{{checkParam(userInfo.follows)}}</text>
                  <text class="relation-item">&nbsp;关注</text>
                </view>&nbsp;&nbsp;
                <view>
                  <text class="relation-number">{{checkParam(userInfo.fans)}}</text>
                  <text class="relation-item">&nbsp;粉丝</text>
                </view>
              </view>

              <view v-if="!owner" class="operation">
                <view @tap.stop="toPrivateChat" v-if="!owner" class="send-msg">私信</view>&nbsp;&nbsp;
                <view  @tap.stop="followUser()" v-if="!userInfo?.isFollowed" class="follow">关注</view>
                <view @tap.stop="followUser()" v-if="userInfo?.isFollowed" class="followed">已关注</view>
              </view>
            </view>
            <view class="introduction" v-if="userInfo.introduction !== ''">{{ userInfo.introduction }}</view>
            <view style="color: #9a9a9a;display: flex;align-items: center" v-else>
              点击添加介绍，让大家认识你...
              <u-icon name="edit-pen"></u-icon>
            </view>
            <view class="ip">
              <!--性别年龄-->
              <view v-if="(userInfo?.sex != 3 && userInfo?.sex != null) || userInfo?.birthday !== ''" class="sex">
                <view
                    v-if="(userInfo?.sex != 3 && userInfo?.sex != null) || (userInfo?.sex != 3 && userInfo?.sex !== undefined) "
                    style="display: flex;align-items: center;">
                  <image style="margin-right: 5px"
                         :src="userInfo?.sex == 1 ? 'http://www.douluodalu.icu:9000/school/static/man_active.png' : 'http://www.douluodalu.icu:9000/school/static/woman_active.png' ">
                  </image>
                  <text v-if="userInfo?.sex == 1">男</text>
                  <text v-if="userInfo?.sex == 0">女</text>
                </view>
                <text v-if="userInfo?.birthday !== '' && userInfo?.birthday !== this.$NOT_SHOW_BIRTH">
                  {{ calculateAge(userInfo?.birthday) }}
                </text>
              </view>

              <!--          地区-->
              <text v-if="oversea != true && userInfo.location?.province != ''">
                {{ userInfo.location?.province }}
              </text>
              <text
                  v-if="oversea == true && (userInfo.location?.country != '' && userInfo?.location?.country !== undefined)">
                {{ userInfo.location.country }}
              </text>

              <view
                  v-if="(userInfo?.birthday === '' ||  userInfo?.birthday == this.$NOT_SHOW_BIRTH)&& (userInfo?.location?.province === undefined && userInfo?.location?.province === '')"
                  class="age">
                <u-icon size="14" name="plus"></u-icon>
                <text>添加年龄、所在地等标签</text>
              </view>
              <view
                  v-if="(userInfo?.birthday === '' ||  userInfo?.birthday == this.$NOT_SHOW_BIRTH) && userInfo?.school === ''"
                  class="age">
                <u-icon size="14" name="plus"></u-icon>
                <text>添加年龄、学校等标签</text>
              </view>
              <view v-if="userInfo?.school === '' &&
            (userInfo?.birthday !== '' &&  userInfo?.birthday != this.$NOT_SHOW_BIRTH)&&
            (userInfo?.location?.province !== undefined || userInfo?.location?.country.trim() !== '')" class="age">
                <u-icon size="14" name="plus"></u-icon>
                <text>添加学校等标签</text>
              </view>
              <view class="age" v-if="userInfo.school !== ''">
                {{ userInfo.school }}
              </view>

            </view>
          </view>
          <view>
            <view class="head-wrapper">
              <u-tabs
                  :current="tagIndex"
                  @click="toScroll"
                  :list="list4"
                  lineWidth="20"
                  lineHeight="7"
                  :lineColor="`url(${lineBg}) 100% 100%`"
                  :activeStyle="{
        color: '#303133',
        fontWeight: 'bold',
        transform: 'scale(1.05)'
    }"
                  :inactiveStyle="{
        color: '#606266',
        transform: 'scale(1)'
    }"
                  itemStyle="padding-left: 5rem; padding-right: 5rem; height: 34px;"
              >
              </u-tabs>
            </view>
            <view class="content-swiper">
              <swiper :current="tagIndex"
                      class="swiper"
                      :circular="false"
                      @change="swiperChange"
                      swiperDuration="250">
                <swiper-item>
                  <BlogForMy v-for="(post,index) in myPostList"
                             :key="index" :post="post"/>
                  <view style="height: 50px;"></view>

                </swiper-item>
                <swiper-item>
                  <BlogForMy v-for="(post,index) in myCollectionList"
                             :key="index" :post="post"
                  />
                  <view style="height: 50px;"></view>

                </swiper-item>
              </swiper>
            </view>
          </view>
        </view>
      </view>

    </scroll-view>
  </view>
</template>

<script>

import {
  getAvatarUrl, getBackgroundUrl,
  getNickName,
  getToken,
  removeAvatarUrl,
  removeExpiresIn,
  removeNickName,
  removeLocation,
  removeToken, removeUserId, getUserId
} from "@/utils/auth";
import {calculateAge} from "@/utils/format";
import Blog from "@/components/Blog.vue";
import {logout} from "@/utils/api";
import tabbar from "@/components/tabbar/tabbar.vue";
import {followUser, getFrontUserInfo, getMyCollections, getMyLikeNum, getMyPostList} from "@/api/user";
import BlogForMy from "@/components/BlogForMy.vue";
import user from "@/store/user";
import {downloadTempFile} from "@/utils/downloadFile";
import colorThief from "miniapp-color-thief";
import UserNotExist from "@/components/skeleton/UserNotExist.vue";


export default {
  components: {UserNotExist, BlogForMy, Blog, tabbar},

  data() {
    return {
      showRightList: false,
      exist: false,
      nickName: '',
      loading: true,
      avatarUrl: '',
      backgroundUrl: '',
      show: false,
      postLoading: true,
      chanelLoading: true,
      collectionLoading: true,
      isPostEmpty: false,
      isChanelEmpty: false,
      isCollectionEmpty: false,
      indexList: [],
      notifyIndex: 0,
      postParams: {
        current: 1,
        pageSize: 15
      },
      chanelParams: {
        current: 1,
        pageSize: 15
      },
      collectionParams: {
        current: 1,
        pageSize: 15
      },
      myPostList: [],
      myChanelList: [],
      myCollectionList: [],
      myLikeNum: 0,
      tagIndex: 0,
      userId: '',
      lineBg: "",
      list4: [
        {name: '帖子'},
        {name: '收藏'}
      ],
      userInfo: {},
      oversea: null,
      owner: false,
      bgHeight: '14rem'
    };
  },
  onShow() {

  },
  onLoad(options) {
    uni.removeStorageSync('bgcUrl')
    uni.removeStorageSync('bgcColor')
    const systemInfo = uni.getSystemInfoSync();
    this.getUserInfo(options.id)
    this.owner = options.id == getUserId()
    this.getMyPostList(options.id)
    this.getMyCollectionList(options.id)

    this.$nextTick(() => {
      this.loading = false
    })
  },
  unload() {
  },
  methods: {
    checkParam(value) {
      if (value === '' || value === undefined || value === null || value < 0) {
        if (typeof value === 'number') {
          return 0;
        }
        if (typeof value === 'string') {
          return '无';
        }
      } else {
        return value;
      }
    },

    toPrivateChat(){
      let token = getToken();
      if (!(token !== null && token !== '' && token !== undefined)) {
        uni.showToast({
          title: '请先登录',
          icon: 'none'
        })
        setTimeout(() => {
          uni.navigateTo({url: '/pages/my/login'})
        }, 500)
        return;
      }
      uni.navigateTo({
        url: `/pages/msg/chat1?userId=${this.userInfo.userId}`
      })
    },
    async followUser() {
      let token = getToken();
      if (!(token !== null && token !== '' && token !== undefined)) {
        uni.showToast({
          title: '请先登录',
          icon: 'none'
        })
        setTimeout(() => {
          uni.navigateTo({url: '/pages/my/login'})
        }, 500)
        return;
      }
      if(this.userInfo?.isFollowed){
        uni.showModal({
          content: '确定要取消关注吗？',
          success: async (res) => {
            if (res.confirm) {
              const res = await followUser(this.userInfo.userId,false)
              if(res.code == 200){
                this.userInfo.isFollowed = false
                uni.showToast({title: '取消关注成功',icon: 'none'})
              }
            } else if (res.cancel) {
              console.log('用户点击取消');
            }
          }
        })
      }else {
        const res = await followUser(this.userInfo.userId,true)
        if(res.code == 200){
          this.userInfo.isFollowed  = true
          uni.showToast({title: '关注成功',icon: 'none'})
        }
      }
    },
    async bgcDownload(file) {
      let bgcUrl = uni.getStorageSync('bgcUrl')
      let result = await downloadTempFile(file, bgcUrl)
    },
    toAlterBackgroud(url) {
      uni.navigateTo({
        url: `/pages/my/alterBackGround?url=${url}`
      })
    },
    toAlterAvatar(url) {
      uni.navigateTo({
        url: `/pages/my/alterAvatar?url=${url}`
      })
    },
    user,
    calculateAge,
    async getUserInfo(id) {
      const res = await getFrontUserInfo(id)
      if (res.code == 200 && res.data?.avatar !== undefined) {
        this.exist = true
        this.userInfo.username = res.data?.username === undefined ? '' : res.data.username
        this.userInfo.birthday = (res.data?.birthday === undefined || res.data?.birthday == this.$NOT_SHOW_BIRTH) ? '' : res.data.birthday
        this.userInfo.location = res.data.location
        this.userInfo.userId = res.data.userId
        this.oversea = res.data?.oversea
        this.userInfo.fans = res.data?.fans
        this.userInfo.follows = res.data?.follows
        this.userInfo.isFollowed = res.data?.isFollowed
        this.userInfo.friends = res.data?.friends
        this.userInfo.likes = res.data?.likes
        this.userInfo.sex = res.data?.sex === undefined ? '' : res.data.sex
        this.userInfo.introduction = res.data?.introduction === undefined ? '' : res.data.introduction
        this.userInfo.avatar = res.data?.avatar

        this.userInfo.school = res.data?.school === undefined ? '' : res.data.school
        let storageSync = uni.getStorageSync('bgcUrl');
        if (storageSync == null || storageSync == undefined || storageSync == '') {
          this.userInfo.backgroundUrl = res.data?.backgroundUrl === undefined ? this.$DEFAULT_BG : res.data.backgroundUrl
          await this.bgcDownload(res.data?.backgroundUrl)
        } else {
          this.userInfo.backgroundUrl = storageSync
        }
        // this.userInfo. = res.data
      } else {
        uni.showToast({
          title: res.data,
          duration: 1500
        })
        setTimeout(() => {
          uni.navigateBack({
            delta: 1
          })
        }, 1500)

      }
      // console.log(this.userInfo)
    },
    async getMyPostList(id) {
      const res = await getMyPostList(id, this.postParams.current, this.postParams.pageSize)
      if (res.code == 200) {
        this.isPostEmpty = res.data?.records?.length == 0
        if (!this.isPostEmpty) {
          this.myPostList = res.data.records
        }
        this.postLoading = false
      }
    },
    async getMyCollectionList(id) {
      const res = await getMyCollections(id, this.collectionParams.current, this.collectionParams.pageSize)
      if (res.code == 200) {
        this.isCollectionEmpty = res.data?.records?.length == 0
        if (!this.isCollectionEmpty) {
          this.myCollectionList = res.data.records
        }
        this.collectionLoading = false
      }
    },
    async getMyLikeNum(id) {
      const res = await getMyLikeNum(id)
      if (res.code == 200) {
        this.myLikeNum = res.data
      }
    },
    logout() {
      uni.showModal({
        title: '确定退出登录?',
        cancelText: '取消',
        confirmText: '确定',
        confirmColor: '#4ea4f9',
        success(res) {
          if (res.confirm) {
            logout().then(res => {
              console.log(res)
              if (res.code == 200) {
                uni.clearStorageSync()
                setTimeout(() => {
                  uni.reLaunch({
                    url: '/pages/my/my'
                  });
                }, 200)
              }
            })
          } else if (res.cancel) {

          }
        }
      })

    },
    ShowRightList() {
      this.showRightList = true
    },
    open() {
      // console.log('open');
    },
    close() {
      this.showRightList = false
      // console.log('close');
    },
    toLogin() {
      uni.navigateTo({
        url: '/pages/my/login'
      })
    },
    toScroll(event) {
      this.tagIndex = event.index
    },
    swiperChange(event) {
      this.tagIndex = event.detail.current
    },
  }
}
</script>

<style scoped>
.container {
  background: no-repeat center center;
  background-size: cover;
}


.userinfo {
  padding: 0 1rem;
  display: flex;
  align-items: center;

}

.operation {
  display: flex;
  align-items: center;
}

.send-msg {
  padding: 5px 15px;
  background-color: white;
  border-radius: 35rpx;
  color: #4ea4f9;
  border: 1px solid #4ea4f9;
  font-weight: initial;
  font-size: 14px;
}

.followed {
  color: rgba(114, 118, 123, 0.38);
  padding: 5px 15px;
  background-color: #FFFFFF;
  border-radius: 35rpx;
  font-weight: initial;
  font-size: 14px;
}
.follow {
  color: #fff;
  padding: 5px 15px;
  background-color: #4ea4f9;
  border-radius: 35rpx;
  font-weight: initial;
  font-size: 14px;
}

.avatar image {
  border: 2px solid white;
  width: 5rem;
  height: 5rem;
  border-radius: 50%;
}


.name text {
  color: white;
  font-weight: 530;
  font-size: 38rpx;
  margin-left: 20rpx;
}

.content {
  background-color: white;
  margin-top: -25px;
  border-top: 1px solid black;
  border-top-left-radius: 25px;
  border-top-right-radius: 25px;
  padding: 0.3rem 1rem 0 1rem;
}

.relation {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.relation-item {
  color: #999;
  font-size: 24rpx;
}

.relation-number {
  color: #000;
  font-size: 24rpx;
  font-weight: bold;
}

.introduction {
  font-size: 24rpx;
}

.age {
  display: flex;
  align-items: center;
  border-radius: 3px;
  margin-left: 5px;
  color: rgba(84, 87, 87, 0.85);
  background-color: rgba(223, 223, 223, 0.7);
  padding: 3px;
}

.sex {
  display: flex;
  align-items: center;
  border-radius: 3px;
  margin-right: 5px;
  color: rgba(84, 87, 87, 0.85);
  background-color: rgba(223, 223, 223, 0.7);
  padding: 1px;
}

.sex image {
  width: 14px;
  height: 14px;
  padding-left: 4px;
}

.ip text {
  color: rgba(84, 87, 87, 0.85);
  background-color: rgba(223, 223, 223, 0.7);
  border-radius: 3px;
  padding: 3px;
}

.ip {
  display: flex;
  align-items: center;
  margin-top: 0.3rem;
  font-size: 24rpx;
  flex-wrap: wrap;

}

.head-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.head-topic {
  padding-top: 5px;
  width: 25px;
  height: 25px;
}

.search {
  padding-top: 5px;
  padding-right: 5px;
  width: 20px;
  height: 20px;
}


.title {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 60rpx;
}

.swiper {
  height: calc(100vh - 120rpx);
}

.unlogin_content {
  display: flex;
  justify-content: center;
  flex-direction: column;
  font-size: 14px;
  color: #b0b0b0;
}

.wrap_content {
  border-radius: 20rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  background: gray;
  height: 100vh;
  color: aqua;
  font-size: 80px;
  margin: 0rpx 40rpx;
}
</style>
